/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.common.annotation.valid.enums;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 枚举类参数校验处理类
 *
 * @author jinchunzhao@yzbdl.ac.cn
 * @date 2022-04-24 14:22
 */
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumValid,Object> {

	/**
	 * 枚举校验注解
	 */
	private EnumValid annotation;

	@Override
	public void initialize(EnumValid constraintAnnotation) {
		annotation = constraintAnnotation;
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
		boolean result = false;
		Class<?> target = annotation.target();
		boolean ignoreEmpty = annotation.ignoreEmpty();

		// target是枚举，并且value有值或者不忽略空值，才进行校验
		if (target.isEnum() && (Objects.nonNull(value) || !ignoreEmpty)){
			Object[] objects = target.getEnumConstants();
			Method method;
			try {

				method = target.getMethod("getCode");
				for (Object object : objects) {
					Object code = method.invoke(object);
					if (Objects.equals(value, code)){
						result = true;
						break;
					}
				}
			}catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e){
				result = false;
			}
		}else {
			result = true;
		}
		return result;
	}
}
